/**
 * 监控中间件
 * 用于记录API调用、性能数据和系统指标
 */

const logger = require('../../logger');

/**
 * 性能监控中间件
 * 记录请求处理时间和性能指标
 */
function performanceMonitor(req, res, next) {
    const startTime = Date.now();
    const originalSend = res.send;
    
    // 拦截响应，添加性能信息
    res.send = function(body) {
        const endTime = Date.now();
        const processingTime = endTime - startTime;
        
        // 记录性能数据
        logger.info({
            message: 'API请求性能日志',
            endpoint: req.originalUrl,
            method: req.method,
            status: res.statusCode,
            processingTime: `${processingTime}ms`,
            ip: req.ip,
            userAgent: req.headers['user-agent'],
            userId: req.user ? req.user.id : null
        });
        
        // 检查是否超过性能阈值
        if (processingTime > 1000) { // 超过1秒
            logger.warn({
                message: 'API请求处理时间过长',
                endpoint: req.originalUrl,
                method: req.method,
                processingTime: `${processingTime}ms`
            });
        }
        
        // 调用原始的send方法
        return originalSend.call(this, body);
    };
    
    next();
}

/**
 * 错误监控中间件
 * 捕获并记录错误，发送警报
 */
function errorMonitor(err, req, res, next) {
    // 记录错误信息
    logger.error({
        message: 'API请求错误',
        error: err.message,
        stack: err.stack,
        endpoint: req.originalUrl,
        method: req.method,
        ip: req.ip,
        userId: req.user ? req.user.id : null
    });
    
    // 检查错误严重程度，发送警报
    if (err.status >= 500) {
        logger.error({
            message: '严重错误警报',
            error: err.message,
            endpoint: req.originalUrl,
            timestamp: new Date().toISOString()
        });
    }
    
    next(err);
}

/**
 * 流量监控中间件
 * 记录API调用频率和趋势
 */
let requestCount = 0;
let lastResetTime = Date.now();

function trafficMonitor(req, res, next) {
    // 增加请求计数
    requestCount++;
    
    // 每分钟重置计数并记录
    const now = Date.now();
    if (now - lastResetTime > 60000) { // 1分钟
        logger.info({
            message: 'API流量统计',
            requestCount,
            timeWindow: '1min',
            timestamp: new Date(now).toISOString()
        });
        requestCount = 0;
        lastResetTime = now;
    }
    
    next();
}

/**
 * 资源使用监控中间件
 * 记录系统资源使用情况
 */
function resourceMonitor(req, res, next) {
    // 记录内存使用情况
    const memoryUsage = process.memoryUsage();
    
    // 仅在高负载时记录详细信息
    if (memoryUsage.rss > 500 * 1024 * 1024) { // 超过500MB
        logger.info({
            message: '内存使用监控',
            rss: `${Math.round(memoryUsage.rss / (1024 * 1024))}MB`,
            heapTotal: `${Math.round(memoryUsage.heapTotal / (1024 * 1024))}MB`,
            heapUsed: `${Math.round(memoryUsage.heapUsed / (1024 * 1024))}MB`
        });
    }
    
    next();
}

/**
 * 用户活动监控中间件
 * 记录用户操作行为
 */
function userActivityMonitor(req, res, next) {
    if (req.user) {
        const sensitiveOperations = ['DELETE', 'PUT', 'POST'];
        const adminEndpoints = req.originalUrl.includes('/admin/');
        
        // 记录用户敏感操作
        if (sensitiveOperations.includes(req.method) || adminEndpoints) {
            logger.info({
                message: '用户活动记录',
                userId: req.user.id,
                username: req.user.username,
                role: req.user.role,
                operation: `${req.method} ${req.originalUrl}`,
                ip: req.ip,
                timestamp: new Date().toISOString()
            });
        }
    }
    
    next();
}

module.exports = {
    performanceMonitor,
    errorMonitor,
    trafficMonitor,
    resourceMonitor,
    userActivityMonitor
};